import { Component, Input, OnInit, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized } from '@angular/router';

@Component({
  selector: 'pagination',
  templateUrl: './pagination.component.html',
  styleUrls: ['./pagination.component.css', '../../app.component.css']
})
export class PaginationComponent implements OnInit, OnChanges {
  showAfterDot: boolean = false;
  showBeforeDot: boolean = false;
  maxPage: number;
  jump: number;
  showList: Array<number>;
  @Input() total: number;
  @Input() pageSize: number = 10;
  @Input() nowPage: number = 1;
  @Output() nowPageChange = new EventEmitter();
  @Output() paginationEvent = new EventEmitter();
  constructor() {
    this.showList = [];
  }
  ngOnInit(): void {
    this.draw();
  }

  private draw() {
    this.showList = [];
    this.showBeforeDot = false;
    this.showAfterDot = false;
    if (this.total == 0) return;
    this.maxPage = Math.ceil(this.total / this.pageSize);

    if (this.nowPage <= 3) {
      if (this.maxPage <= 6) {
        for (let i = 2; i <= this.maxPage - 1; i++) {
          this.showList.push(i);
        }
      }

      if (this.maxPage > 6) {
        for (let i = 2; i <= 5; i++) {
          this.showList.push(i);
        }
        this.showAfterDot = true;
      }
    } else {
      if (this.nowPage - 2 > 1) {
        this.showList.push(this.nowPage - 2);
        if (this.nowPage - 2 > 2) {
          this.showBeforeDot = true;
        }
      }
      if (this.nowPage - 1 > 1) {
        this.showList.push(this.nowPage - 1);
      }
      if(this.nowPage!=this.maxPage){
        this.showList.push(this.nowPage);
      }
      
      if (this.nowPage + 1 < this.maxPage) {
        this.showList.push(this.nowPage + 1);
      }

      if (this.nowPage + 2 < this.maxPage) {
        this.showList.push(this.nowPage + 2);
        if (this.nowPage + 2 < this.maxPage - 1) {
          this.showAfterDot = true;
        }
      }
    }
  }

  jumpPage(page?) {
    if (page == null) {
      this.nowPage = this.jump;
    } else {
      if (page == 'before') {
        if (this.nowPage == 1) {
          return;
        }
        this.nowPage = this.nowPage - 1;
      } else
        if (page == 'after') {
          if (this.nowPage == this.maxPage) {
            return;
          }
          this.nowPage = this.nowPage + 1;
        } else {
          this.nowPage = page;
        }
    }

    if (this.nowPage > this.maxPage) {
      this.nowPage = this.maxPage;
    }

    this.draw();
    this.nowPageChange.emit(this.nowPage);
    this.paginationEvent.emit();
  }

  pressInput(event) {
    if (event.key == 'Enter') {
      this.jumpPage();
      this.jump = null;
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (!changes.total.firstChange) {
      this.draw();
    }
  }
}
